/* eslint-disable jsx-a11y/href-no-hash */
import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import { Input, Button } from 'antd';
import { createForm } from 'rc-form';
import JsSha from 'jssha';
import Page from '../Page/PageComponent';
import CreateTokenMutation from '../../relay/account/CreateTokenMutation';
import LocalStorage from '../../utils/localStorage';
import * as constants from '../../constants';

class Form extends Component {
  submit = () => {
    this.props.form.validateFields((error, value) => {
      if (error) {

      } else {
        const sha = new JsSha('SHA3-224', 'TEXT');
        sha.update(value.password);
        Relay.Store.commitUpdate(
          new CreateTokenMutation(Object.assign({}, value, { password: sha.getHash('HEX') })),
          {
            onSuccess: ({ createToken }) => {
              if (createToken.error){
                alert(createToken.error)
              } else{
                LocalStorage.set(constants.FIELDS.ORGANIZATION_ID, createToken.viewer.company.id, 60*60*24);
                LocalStorage.set(constants.FIELDS.TOKEN_NAME, createToken.token, 60 * 60 * 24);
                LocalStorage.set(constants.FIELDS.USER_NAME, value.name);
                setTimeout(this.context.router.push('/'), 100);
              }
            },
            onFailure: (error) => {
              console.log('error')
            },
          });
      }
    });
  }

  render() {
    let errors;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div>
        <Input
          placeholder="用户名"
          {...getFieldProps('name', {
            rules: [{ required: true }],
          })}
        />
        <div style={{ margin: '24px 0' }} />
        <Input
          placeholder="密码"
          {...getFieldProps('password', {
            rules: [{ required: true }],
          })}
        />
        <div style={{ margin: '24px 0' }} />
        <Button
          onClick={this.submit}
        >登录</Button>
      </div>
    )
  }
}

Form.contextTypes = {
  router: PropTypes.object,
};

const MyForm = createForm()(Form);

export default class Login extends Component {
  render() {
    return (
      <Page>
        <div style={{ width: '300px', margin: 'auto', marginTop: '80px' }}>
          <h3>登录</h3>
          <MyForm />
        </div>
      </Page>
    );
  }
}
